package com.yimingkeji.thymeleaf.web;

import com.yimingkeji.thymeleaf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

/**
 * @Describe:
 * @Auther: zhenlong.yang
 * @Date: 2018/12/14 19:34
 */
@Controller
public class UserController {

    @Autowired private UserService userService;

    @GetMapping("/")
    public String index(){
        return "redirect:/list";
    }

    @GetMapping("/list")
    public String list(Model model){
        List<UserService.User> list = userService.list();
        model.addAttribute("list", list);
        return "list";
    }

    @GetMapping("/toAdd")
    public String toAdd(){
        return "add";
    }

    @PostMapping("/add")
    public String add(UserService.User user){
        userService.save(user);
        return "redirect:/list";
    }

    @GetMapping("/toEdit/{id}")
    public String toEdit(@PathVariable int id, Model model){
        UserService.User user = userService.get(id);
        model.addAttribute("user", user);
        return "edit";
    }

    @PostMapping("/edit")
    public String edit(UserService.User user){
        userService.save(user);
        return "redirect:/list";
    }

    @GetMapping("/delete")
    public String delete(int id){
        userService.del(id);
        return "redirect:/list";
    }
}
